package a51qindian.com.comprehensive.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;

import com.li.interfaces.OnItemClickListener;
import com.li.utils.TransformUtil;
import com.li.widget.DoubleTextView;
import com.li.widget.MultipleLayout;
import com.li.widget.TopNavigationBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import a51qindian.com.comprehensive.Const;
import a51qindian.com.comprehensive.R;
import a51qindian.com.comprehensive.adapter.AgentAdapter;
import a51qindian.com.comprehensive.base.QDBaseActivity;
import a51qindian.com.comprehensive.items.LinearItemDecoration;
import a51qindian.com.comprehensive.model.AgentInfo;
import a51qindian.com.comprehensive.model.CountBaseModel;
import a51qindian.com.comprehensive.net.ObservableHelper;
import a51qindian.com.comprehensive.net.RetrofitCreator;
import a51qindian.com.comprehensive.net.SelectorObserver;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**
 * Author: Li
 * Date: 2017/10/24 0024
 * Description: 区代列表
 */

public class AgentListActivity extends QDBaseActivity {

    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.recycler_agent)
    SwipeMenuRecyclerView mRecyclerAgent;
    @BindView(R.id.layout_refresh)
    SmartRefreshLayout mLayoutRefresh;
    @BindView(R.id.layout_content)
    MultipleLayout mLayoutContent;
    @BindView(R.id.dtv_num)
    DoubleTextView mDtvNum;


    private AgentAdapter mAgentAdapter;
    private List<AgentInfo> mAgentInfoList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_agent_list;
    }


    // 创建菜单：
    SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {
            SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
            deleteItem.setText("删除");
            deleteItem.setBackgroundColor(Color.RED);
            deleteItem.setHeight(-1);
            deleteItem.setWidth(TransformUtil.dp2px(mContext,70));
            deleteItem.setTextColor(Color.WHITE);
            rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
        }
    };
    // 菜单点击监听。
    SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
            menuBridge.closeMenu();

            final int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。

            Log.e("tag", "onItemClick: "+adapterPosition);
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
                    .setTitle("提示")
                    .setMessage("是否删除该区代：" + mAgentInfoList.get(adapterPosition).getRealname())
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            deleteAgent(mUid, mAgentInfoList.get(adapterPosition).getUid(), adapterPosition);
                        }
                    });
            builder.create().show();
        }
    };

    @Override
    protected void initSth() {
        super.initSth();
        mAgentInfoList = new ArrayList<>();
        mTopNavigation.setNavigationBarListener(this);
        setSmartRefreshLayout(mLayoutRefresh);
        mRecyclerAgent.setLayoutManager(new LinearLayoutManager(this));
        mAgentAdapter = new AgentAdapter(this);
        mRecyclerAgent.addItemDecoration(new LinearItemDecoration());
        mAgentAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int pos) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
                        .setTitle("提示")
                        .setMessage("是否拨打电话：" + mAgentInfoList.get(pos).getMobile())
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent=new Intent(Intent.ACTION_DIAL);
                                intent.setData(Uri.parse("tel:"+mAgentInfoList.get(pos).getMobile()));
                                startActivity(intent);
                            }
                        });
                builder.create().show();
            }
        });

        mRecyclerAgent.setSwipeMenuCreator(mSwipeMenuCreator);
        mRecyclerAgent.setSwipeMenuItemClickListener(mMenuItemClickListener);
        mRecyclerAgent.setAdapter(mAgentAdapter);

    }


    @Override
    protected void onResume() {
        super.onResume();
        mPage = 0;
        mIsRefresh = true;
        showAgentList(mUid, String.valueOf(mPage));
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        super.onLoadmore(refreshlayout);
        showAgentList(mUid, String.valueOf(mPage + 1));
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        super.onRefresh(refreshlayout);
        showAgentList(mUid, Const.DEFAULT_PAGE);

    }

    @Override
    public void onFunctionImgListener(View view) {
        super.onFunctionImgListener(view);
        mRecyclerAgent.smoothCloseMenu();
        startActivity(new Intent(this, AddAgentActivity.class));
    }

    /**
     * 显示区代列表
     *
     * @param uid  用户编号
     * @param page 页数
     */
    private void showAgentList(String uid, String page) {
        mLayoutContent.onLoadingWithContent();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page", page);
        ObservableHelper.createObservable(RetrofitCreator.createService().agentList(map))
                .subscribe(new SelectorObserver<CountBaseModel<List<AgentInfo>>>() {
                    @Override
                    protected void onErrorCodeInfo(int code, String info) {
                        mLayoutContent.onSuccess();
                        stopRefreshLoad();
                        mLayoutRefresh.setLoadmoreFinished(true);
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(CountBaseModel<List<AgentInfo>> listBaseModel) {
                        mLayoutContent.onSuccess();

                        if (mIsRefresh) {
                            mPage = 0;
                            mAgentInfoList.clear();
                            mLayoutRefresh.setLoadmoreFinished(false);
                        } else {
                            mPage++;
                        }
                        stopRefreshLoad();
                        List<AgentInfo> agentInfoList = listBaseModel.getData();
                        if (!mIsRefresh && agentInfoList.size() < Const.DEFAULT_PAGE_SIZE) {
                            mLayoutRefresh.setLoadmoreFinished(true);
                        }
                        mAgentInfoList.addAll(agentInfoList);
                        mAgentAdapter.setAgentInfoList(mAgentInfoList);
                        mDtvNum.setTxtRight(listBaseModel.getCount());
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                        stopRefreshLoad();
                    }
                });
    }

    /**
     * 删除代理
     *
     * @param uid  账号id
     * @param uuId 要删除的代理id
     * @param pos  更新界面
     */
    private void deleteAgent(String uid, String uuId, final int pos) {
        mLayoutContent.onLoadingWithContent("正在删除");
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("uu_id", uuId);
        ObservableHelper.createObservable(RetrofitCreator.createService().deleteAgent(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        mLayoutContent.onSuccess();
                        try {
                            JSONObject object = new JSONObject(s);
                            showToast(object.getString("info"));
                            if (object.getInt("code") == 1) {
                                mAgentInfoList.remove(pos);
                                mAgentAdapter.notifyItemRemoved(pos);
                                int count = Integer.parseInt(mDtvNum.getTxtRight()) - 1;
                                mDtvNum.setTxtRight(String.valueOf(count));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        mLayoutContent.onSuccess();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}
